/**
 * 数据访问层 - 处理博客数据的 CRUD 操作
 * 使用 Prisma ORM 与 SQLite 数据库交互
 */

import { BlogPost } from './types';
import { prisma } from './prisma';

/**
 * 获取博客文章列表
 * @param status 文章状态筛选（可选）
 * @returns 博客文章数组
 */
export const getBlogPosts = async (status?: 'draft' | 'published'): Promise<BlogPost[]> => {
  // 构建查询条件，如果指定了状态则进行筛选
  const where = status ? { status: status.toUpperCase() as any } : {};
  
  // 从数据库查询文章，包含关联的作者和标签信息
  const posts = await prisma.post.findMany({
    where,
    include: {
      author: {
        select: { name: true }  // 只选择作者姓名
      },
      tags: {
        include: {
          tag: true  // 包含标签的完整信息
        }
      }
    },
    orderBy: { createdAt: 'desc' }  // 按创建时间倒序排列
  });

  // 将数据库查询结果转换为前端需要的格式
  return posts.map(post => ({
    id: post.id,
    title: post.title,
    content: post.content,
    excerpt: post.excerpt,
    author: post.author.name,
    publishedAt: post.publishedAt?.toISOString() || post.createdAt.toISOString(),
    updatedAt: post.updatedAt.toISOString(),
    tags: post.tags.map(pt => pt.tag.name),  // 提取标签名称
    status: post.status.toLowerCase() as 'draft' | 'published',
    slug: post.slug,
    coverImage: post.coverImage || undefined,
    viewCount: post.viewCount  // 包含浏览量
  }));
};

export const getBlogPost = async (slug: string): Promise<BlogPost | null> => {
  const post = await prisma.post.findUnique({
    where: { slug },
    include: {
      author: {
        select: { name: true }
      },
      tags: {
        include: {
          tag: true
        }
      }
    }
  });

  if (!post) return null;

  return {
    id: post.id,
    title: post.title,
    content: post.content,
    excerpt: post.excerpt,
    author: post.author.name,
    publishedAt: post.publishedAt?.toISOString() || post.createdAt.toISOString(),
    updatedAt: post.updatedAt.toISOString(),
    tags: post.tags.map(pt => pt.tag.name),
    status: post.status.toLowerCase() as 'draft' | 'published',
    slug: post.slug,
    coverImage: post.coverImage || undefined,
    viewCount: post.viewCount  // 包含浏览量
  };
};

export const createBlogPost = async (post: Omit<BlogPost, 'id' | 'publishedAt' | 'updatedAt'>): Promise<BlogPost> => {
  // 创建或获取标签
  const tagIds = await Promise.all(
    post.tags.map(async (tagName) => {
      const tag = await prisma.tag.upsert({
        where: { name: tagName },
        update: {},
        create: { name: tagName }
      });
      return tag.id;
    })
  );

  // 创建文章
  const newPost = await prisma.post.create({
    data: {
      title: post.title,
      content: post.content,
      excerpt: post.excerpt,
      slug: post.slug,
      status: post.status.toUpperCase() as any,
      coverImage: post.coverImage,
      publishedAt: post.status === 'published' ? new Date() : null,
      author: {
        connectOrCreate: {
          where: { email: 'admin@example.com' },
          create: {
            email: 'admin@example.com',
            name: post.author,
            password: 'hashed-password'
          }
        }
      },
      tags: {
        create: tagIds.map(tagId => ({
          tagId
        }))
      }
    },
    include: {
      author: {
        select: { name: true }
      },
      tags: {
        include: {
          tag: true
        }
      }
    }
  });

  return {
    id: newPost.id,
    title: newPost.title,
    content: newPost.content,
    excerpt: newPost.excerpt,
    author: newPost.author.name,
    publishedAt: newPost.publishedAt?.toISOString() || newPost.createdAt.toISOString(),
    updatedAt: newPost.updatedAt.toISOString(),
    tags: newPost.tags.map(pt => pt.tag.name),
    status: newPost.status.toLowerCase() as 'draft' | 'published',
    slug: newPost.slug,
    coverImage: newPost.coverImage || undefined
  };
};

export const updateBlogPost = async (id: string, updates: Partial<Omit<BlogPost, 'id' | 'publishedAt'>>): Promise<BlogPost | null> => {
  const existingPost = await prisma.post.findUnique({
    where: { id }
  });

  if (!existingPost) return null;

  // 处理标签更新
  let tagIds: string[] = [];
  if (updates.tags) {
    tagIds = await Promise.all(
      updates.tags.map(async (tagName) => {
        const tag = await prisma.tag.upsert({
          where: { name: tagName },
          update: {},
          create: { name: tagName }
        });
        return tag.id;
      })
    );
  }

  // 更新文章
  const updateData = {
    ...updates,
    publishedAt: updates.status === 'published' && existingPost.status !== 'PUBLISHED' 
      ? new Date() 
      : existingPost.publishedAt
  };

  // 移除 tags 字段，单独处理
  delete (updateData as any).tags;

  const updatedPost = await prisma.post.update({
    where: { id },
    data: updateData,
    include: {
      author: {
        select: { name: true }
      },
      tags: {
        include: {
          tag: true
        }
      }
    }
  });

  // 如果更新了标签，重新创建关联
  if (updates.tags) {
    await prisma.postTag.deleteMany({
      where: { postId: id }
    });

    await prisma.postTag.createMany({
      data: tagIds.map(tagId => ({
        postId: id,
        tagId
      }))
    });

    // 重新获取更新后的文章
    const finalPost = await prisma.post.findUnique({
      where: { id },
      include: {
        author: {
          select: { name: true }
        },
        tags: {
          include: {
            tag: true
          }
        }
      }
    });

    if (!finalPost) return null;

    return {
      id: finalPost.id,
      title: finalPost.title,
      content: finalPost.content,
      excerpt: finalPost.excerpt,
      author: finalPost.author.name,
      publishedAt: finalPost.publishedAt?.toISOString() || finalPost.createdAt.toISOString(),
      updatedAt: finalPost.updatedAt.toISOString(),
      tags: finalPost.tags.map(pt => pt.tag.name),
      status: finalPost.status.toLowerCase() as 'draft' | 'published',
      slug: finalPost.slug,
      coverImage: finalPost.coverImage || undefined
    };
  }

  return {
    id: updatedPost.id,
    title: updatedPost.title,
    content: updatedPost.content,
    excerpt: updatedPost.excerpt,
    author: updatedPost.author.name,
    publishedAt: updatedPost.publishedAt?.toISOString() || updatedPost.createdAt.toISOString(),
    updatedAt: updatedPost.updatedAt.toISOString(),
    tags: updatedPost.tags.map(pt => pt.tag.name),
    status: updatedPost.status.toLowerCase() as 'draft' | 'published',
    slug: updatedPost.slug,
    coverImage: updatedPost.coverImage || undefined
  };
};

export const deleteBlogPost = async (id: string): Promise<boolean> => {
  try {
    await prisma.post.delete({
      where: { id }
    });
    return true;
  } catch {
    return false;
  }
};

export const getBlogStats = async () => {
  const [totalPosts, publishedPosts, draftPosts, totalViews] = await Promise.all([
    prisma.post.count(),
    prisma.post.count({ where: { status: 'PUBLISHED' } }),
    prisma.post.count({ where: { status: 'DRAFT' } }),
    prisma.post.aggregate({
      _sum: {
        viewCount: true
      }
    })
  ]);

  return {
    totalPosts,
    publishedPosts,
    draftPosts,
    totalViews: totalViews._sum.viewCount || 0 // 计算所有文章的总浏览量
  };
};
